<?php


namespace app\api\validate;


use app\lib\exception\parameterException;

class OrdersValidate extends BaseValidate
{
    protected $dish = [
        [
            'dish_id' => 1,
            'order_count' => 3
        ],[
            'dish_id' => 2,
            'order_count' => 3
        ],[
            'dish_id' => 3,
            'order_count' => 3
        ]
    ];
    protected $oDish = [
        [
            'dish_id' => 1,
            'order_count' => 1
        ],[
            'dish_id' => 2,
            'order_count' => 2
        ],[
            'dish_id' => 3,
            'order_count' => 2
        ]
    ];

    // 验证订单
    protected $rule = [
        'products' => 'checkDish'
    ];

    // 验证订单里商品的字段
    protected $singleRule = [
        'dish_id' => 'require|isInt',
        'order_count' => 'require|isInt'
    ];

    protected function checkDish($values)
    {
        // 是否为数组
        if (!is_array($values)) {
            throw new parameterException([
                'msg' => '商品参数不正确'
            ]);
        }
        if (empty($values)) {
            throw new parameterException([
                'msg' => '商品列表不能为空'
            ]);
        }
        // 遍历商品
        foreach ($values as $value) {
            $this->checkSingleDish($value);
        }
        // 遍历后没有异常
        return true;
    }

    protected function checkSingleDish($value)
    {
        // 手动调用验证方法
        $validate = new BaseValidate($this->singleRule);
        $result = $validate->check($value);
        if (!$result) {
            throw new parameterException([
                'msg' => '商品列表参数错误'
            ]);
        }
    }
}